package com.gthncz;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class InstanceDemo implements Serializable, Cloneable {

    private int data;

    public InstanceDemo() {}
    public InstanceDemo(int data) {this.data = data;}

    public static void main(String[] args) {
        // 1. new
        InstanceDemo demo1 = new InstanceDemo();

        // 2. 反射
        try {
            InstanceDemo demo2 = (InstanceDemo) Class.forName("com.gthncz.InstanceDemo").newInstance();
            InstanceDemo demo3 = InstanceDemo.class.newInstance();

            Constructor<InstanceDemo> constructor = InstanceDemo.class.getConstructor();
            InstanceDemo demo4 = constructor.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // getConstructor()
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // constructor.newInstance()
            e.printStackTrace();
        }

        // 3. 反序列化
        InstanceDemo tmp = new InstanceDemo();
        File file = new File("./instance.obj");
        try {
            FileOutputStream foo = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(foo);
            oos.writeObject(tmp);
            oos.flush();
            foo.close();
            oos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ios = new ObjectInputStream(fis);
            InstanceDemo demo5 = (InstanceDemo) ios.readObject();
            System.out.println(tmp == demo5);
            ios.close();
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        // 4. 克隆
        try {
            InstanceDemo demo6 = (InstanceDemo) demo1.clone();
            System.out.println(demo1 == demo6);
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }

        file.delete();
    }
}
